package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.service.ShortMsgService;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 短信服务接口实现类
 * @author 李平
 * @Date 2022-5-1
 */
@Service
public class ShortMsgServiceImpl implements ShortMsgService {

    /**
     * 发送短信验证码
     * @param phone
     * @param code
     * @return Boolean
     */
    @Override
    public Boolean sendShortMsg(String phone, Map<String, Object> code) {
        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen", "LTAI5tNQwFLnAgmwpQKfcd3o",
                "5ZQMsPXxuZlYrHREp197YrJY9Izjhl");
        IAcsClient client = new DefaultAcsClient(profile);
        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        // 自定义的参数,手机号,验证码,签名,模板
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "知物GO");
        request.putQueryParameter("TemplateCode", "SMS_239318538");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            // 构建成功返回true
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        // 构建失败返回false
        return false;
    }
}
